package com.tydic.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tydic.system.domain.SysMenu;
import com.tydic.system.domain.bo.QuerySysMenuBo;
import com.tydic.system.domain.vo.SysMenuVo;
import com.tydic.system.mapper.SysMenuMapper;
import com.tydic.system.mapper.SysRoleMapper;
import com.tydic.system.mapper.SysRoleMenuMapper;
import com.tydic.system.mapper.SysTenantPackageMapper;
import com.tydic.system.service.ISysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 菜单 业务层处理
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysMenuServiceImpl implements ISysMenuService {

    private final SysMenuMapper baseMapper;
    private final SysRoleMapper roleMapper;
    private final SysRoleMenuMapper roleMenuMapper;
    private final SysTenantPackageMapper tenantPackageMapper;


    @Override
    public List<SysMenuVo> queryList(QuerySysMenuBo bo) {
        return baseMapper.selectVoList(buildLambdaQueryWrapper(BeanUtil.toBean(bo, SysMenu.class)));
    }

    private LambdaQueryWrapper<SysMenu> buildLambdaQueryWrapper(SysMenu sysMenu) {
        LambdaQueryWrapper<SysMenu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CharSequenceUtil.isNotBlank(sysMenu.getParentCode()), SysMenu::getParentCode, sysMenu.getParentCode());
        lqw.like(CharSequenceUtil.isNotBlank(sysMenu.getMenuName()), SysMenu::getMenuName, sysMenu.getMenuName());
        return lqw;
    }

    @Override
    public SysMenuVo getById(String menuCode) {
        SysMenuVo sysMenuVo = baseMapper.selectVoById(menuCode);
        SysMenuVo parentMenu = baseMapper.selectVoById(sysMenuVo.getParentCode());
        if (parentMenu != null) {
            sysMenuVo.setParentName(parentMenu.getMenuName());
        }
        return sysMenuVo;
    }

    @Override
    public List<SysMenuVo> queryTree(String parentCode) {
        return queryTree(parentCode, null);
    }

    private List<SysMenuVo> queryTree(String parentCode, String parentName) {
        if (CharSequenceUtil.isBlank(parentCode)) {
            parentCode = "0";
        }
        SysMenu sysMenu = new SysMenu();
        sysMenu.setParentCode(parentCode);
        LambdaQueryWrapper<SysMenu> lqw = buildLambdaQueryWrapper(sysMenu);
        List<SysMenuVo> tree = baseMapper.selectVoList(lqw);
        tree.forEach(item -> {
            item.setParentName(parentName);
            item.setChildren(queryTree(item.getMenuCode(), item.getMenuName()));
        });
        return tree;
    }
}
